package servlets;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        handleCors(resp);
        HttpSession session = req.getSession();
        session.setAttribute("user", "zzr");
        resp.setContentType("application/json");
        resp.getWriter().write("{\"code\":200,\"msg\":\"登录成功\"}");
    }

    //    对于某些 HTTP 请求（如带有自定义头或使用非简单方法的请求），浏览器会在发送实际请求之前先发送一个 OPTIONS 请求以确定服务器是否允许该实际请求。
    //    你需要处理这些 OPTIONS 请求并返回适当的 CORS 头信息。
    @Override
    protected void doOptions(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        handleCors(response);
        response.setStatus(HttpServletResponse.SC_OK);
        System.out.println("doPptions is called");
    }
    private void handleCors(HttpServletResponse response)
    {
        response.setHeader("Access-Control-Allow-Origin", "*"
        );
        response.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS"
        );
        response.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Custom-Header"
        );
    }
}
